package com.budwk.app.sqfwV2.service.centuryCity;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.models.Sqfw_form_summary_pdf;
import com.budwk.app.sqfw.services.SqfwFormSummaryPdfService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGeneratorV2.config.ExcelGeneratorConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.excelService.Sqfw2ExcelService;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.ExcelRowDataParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.Sqfw2ExcelGPForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwV2.dto.centuryCity.CenturyCityOldCarePdfDTO;
import com.budwk.app.sqfwV2.enums.centuryCityOldCare.CenturyCityOldCareV2FileEnums;
import com.budwk.app.sqfwV2.generator.centuryCity.CenturyCityOldCareV2BusinessParam;
import com.budwk.app.sqfwV2.generator.centuryCity.ElderlyCareSafetyCheckLedgerExcelGenerator;
import com.budwk.app.sqfwV2.generator.centuryCity.FoodSafetyInsLedgerExcelGenerator;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 东方祥云低代码1.1
 * @since 2024-06-06
 * <p>
 * 世纪城养老服务站巡查1.1 CenturyCityOldCare
 */
@IocBean
public class CenturyCityOldCareExcelService extends Sqfw2ExcelService {

    public static final String nextFormSummaryName = "nextFormSummary";
    public static final String lastFormSummaryName = "lastFormSummary";

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    public List<ResultOfExcelGenerator> createExcel(Sqfw2ExcelGPForController paramForController) {

        String userId = SecurityUtil.getUserId();

        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.OLD_CARE_SERVICE.getName());
        if (null != paramForController.getCustomerParam() && paramForController.getCustomerParam().get("client").equals("web")) {
            CommonCheckUtils.checkAreaRangeCnd(cnd);
            cnd.and(Sqfw_formSummary_new::getId, "IN", paramForController.getCustomerParam().get("summaryIds"));
        } else {
            Date fillStartDate = DateUtil.beginOfDay(paramForController.getFillStartDate());
            Date fillEndDate = DateUtil.endOfDay(paramForController.getFillEndDate());
            cnd.and(Sqfw_formSummary_new::getFillDate, ">=", fillStartDate)
                    .and(Sqfw_formSummary_new::getFillDate, "<=", fillEndDate)
                    .and(Sqfw_formSummary_new::getCreateBy, "=", userId);
        }
        List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(cnd);
        List<String> formSummaryIds = summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList());

        paramForController.setFormSummaryIdList(formSummaryIds);
        paramForController.setUserId(userId);
        paramForController.setFillStartDate(paramForController.getFillStartDate());
        paramForController.setFillEndDate(paramForController.getFillEndDate());
        return super.createExcel(paramForController);
    }

    @Override
    public List<ExcelGeneratorConfig> getExcelGeneratorConfig(List<ExcelCreateConfig> excelCreateConfigList) {
        List<ExcelGeneratorConfig> generatorConfigList = Lists.newArrayList();
        for (ExcelCreateConfig excelCreateConfig : excelCreateConfigList) {
            String fileIdentity = excelCreateConfig.getFileIdentity();

            ExcelGeneratorConfig generatorConfig = new ExcelGeneratorConfig();
            generatorConfig.setExcelCreateConfig(excelCreateConfig);
            if (fileIdentity.equals(CenturyCityOldCareV2FileEnums.elderlyCareInsSafetyInsLedgerExcel.getCode())) {
                generatorConfig.setExcelGenerator(new ElderlyCareSafetyCheckLedgerExcelGenerator());
            }

            if (fileIdentity.equals(CenturyCityOldCareV2FileEnums.foodSafetyInsLedgerExcel.getCode())) {
                generatorConfig.setExcelGenerator(new FoodSafetyInsLedgerExcelGenerator());
            }
            generatorConfigList.add(generatorConfig);
        }
        return generatorConfigList;
    }

    /**
     * 在创建生成参数的时候允许自定义填充数据
     *
     * @param formSummaryNew 表单数据
     */
    public void customerPopularExcelRowDataParam(ExcelRowDataParam rowDataParam, Sqfw_formSummary_new formSummaryNew) {

        CenturyCityOldCareV2BusinessParam businessParam = new CenturyCityOldCareV2BusinessParam();
        businessParam.setFormSummaryNew(formSummaryNew);
        rowDataParam.setBusinessParam(businessParam);

        String paramData = formSummaryNew.getParamData();
        CenturyCityOldCarePdfDTO centuryCityOldCarePdfDTO = JSONObject.parseObject(paramData, CenturyCityOldCarePdfDTO.class);

        // 查询当前数据的下一条检查数据
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getProvince, "=", formSummaryNew.getProvince())
                .and(Sqfw_formSummary_new::getCity, "=", formSummaryNew.getCity())
                .and(Sqfw_formSummary_new::getDistrict, "=", formSummaryNew.getDistrict())
                .and(Sqfw_formSummary_new::getDistrict, "=", formSummaryNew.getDistrict())
                .and(Sqfw_formSummary_new::getCommunity, "=", formSummaryNew.getCommunity())
                .and(Sqfw_formSummary_new::getFillDate, ">", formSummaryNew.getFillDate())
                .and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.OLD_CARE_SERVICE.getName())
                .and(" param_data ->> 'placeName'", "=", centuryCityOldCarePdfDTO.getPlaceName());
        cnd.and(Sqfw_formSummary_new::getId, "!=", formSummaryNew.getId());
        cnd.orderBy(Sqfw_formSummary_new::getFillDate, "asc");
        Sqfw_formSummary_new nextFormSummary = sqfwFormsummaryNewService.fetch(cnd);

        Cnd lastCnd = Cnd.NEW();
        lastCnd.and(Sqfw_formSummary_new::getProvince, "=", formSummaryNew.getProvince())
                .and(Sqfw_formSummary_new::getCity, "=", formSummaryNew.getCity())
                .and(Sqfw_formSummary_new::getDistrict, "=", formSummaryNew.getDistrict())
                .and(Sqfw_formSummary_new::getDistrict, "=", formSummaryNew.getDistrict())
                .and(Sqfw_formSummary_new::getCommunity, "=", formSummaryNew.getCommunity())
                .and(Sqfw_formSummary_new::getFillDate, "<", formSummaryNew.getFillDate())
                .and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.OLD_CARE_SERVICE.getName())
                .and(" param_data ->> 'placeName'", "=", centuryCityOldCarePdfDTO.getPlaceName());
        lastCnd.and(Sqfw_formSummary_new::getId, "!=", formSummaryNew.getId());
        lastCnd.orderBy(Sqfw_formSummary_new::getFillDate, "desc");
        Sqfw_formSummary_new lastFormSummary = sqfwFormsummaryNewService.fetch(lastCnd);

        rowDataParam.getCustomerParamMap().put(nextFormSummaryName, nextFormSummary);
        rowDataParam.getCustomerParamMap().put(lastFormSummaryName, lastFormSummary);
    }

    @Override
    public AbstractCustomerPdfCreateField getAbstractCustomerField(String jsonStr) {
        return JSONObject.parseObject(jsonStr, CenturyCityOldCarePdfDTO.class);
    }

    public String downloadPdf(Date fillStartDate, Date fillEndDate, String fileIdentity) {
        String userId = SecurityUtil.getUserId();

        // 首先查询出所有的formSummary数据
        Cnd cnd = Cnd.NEW()
                .and(Sqfw_formSummary_new::getFillDate, ">=", fillStartDate)
                .and(Sqfw_formSummary_new::getFillDate, "<=", DateUtil.endOfDay(fillEndDate))
                .and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.OLD_CARE_SERVICE.getName())
                .and(Sqfw_formSummary_new::getCreateBy, "=", userId);
        cnd.orderBy(Sqfw_formSummary_new::getFillDate, "asc");

        List<Sqfw_formSummary_new> formSummaryDataList = sqfwFormsummaryNewService.query(cnd);
        Set<String> formSummaryIdSet = formSummaryDataList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toSet());
        if (formSummaryIdSet.size() == 0) return null;

        SqfwFormSummaryPdfService sqfwFormSummaryPdfService = NutzIocUtils.getBean(SqfwFormSummaryPdfService.class);
        Cnd pdfCnd = Cnd.NEW();
        pdfCnd.and(Sqfw_form_summary_pdf::getSummaryId, "in", formSummaryIdSet).and(Sqfw_form_summary_pdf::getIndex, "=", fileIdentity);
        List<Sqfw_form_summary_pdf> pdfList = sqfwFormSummaryPdfService.query(pdfCnd);

        List<String> pdfPathList = Lists.newArrayList();
        for (Sqfw_form_summary_pdf summaryPdf : pdfList) {
            String url = summaryPdf.getUrl();
            url = NutzIocUtils.getOssPrefix() + url;
            pdfPathList.add(url);
        }

        if (pdfPathList.size() == 1) return pdfPathList.get(0);

        String fileType = "";
        for (CenturyCityOldCareV2FileEnums enu : CenturyCityOldCareV2FileEnums.values()) {
            if (enu.getCode().equals(fileIdentity)) {
                fileType = enu.getName();
            }
        }
        String fileName = SupportBusinessTypeEnum.OLD_CARE_SERVICE.getName() + fileType;
        return CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, fileName);
    }

    /**
     * 根据养老院名称查询数据
     *
     * @param placeName 养老院名称
     * @return 结果
     */
    public List<Sqfw_formSummary_new> listOldCarePlaceName(String placeName) {
        String userId = SecurityUtil.getUserId();
        SysUserService sysUserService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user sysUser = sysUserService.fetch(userId);

        String sqlTemplate = " select t1.*  " +
                " from shequ.sqfw_form_summary_new t1 " +
                " JOIN ( " +
                " SELECT " +
                " param_data ->> 'placeName' place_name, " +
                " max(fill_date) fill_date " +
                " FROM " +
                " shequ.sqfw_form_summary_new " +
                " where type = @type " +
                " and param_data ->> 'placeName' like @placeName " +
                " and province = @province " +
                " and city = @city " +
                " and district = @district " +
                " and county = @county " +
                " and community = @community " +
                " GROUP BY param_data ->> 'placeName' " +
                " ) as t2 on t1.fill_date = t2.fill_date and t2.place_name = t1.param_data ->> 'placeName' " +
                " and t1.\"type\" = @type and t1.\"province\" = @province " +
                " and t1.\"city\" = @city " +
                " and t1.\"district\" = @district " +
                " and t1.\"county\" = @county " +
                " and t1.\"community\" = @community ";
        Sql sql = Sqls.create(sqlTemplate);
        sql.setParam("type", SupportBusinessTypeEnum.OLD_CARE_SERVICE.getName());
        sql.setParam("placeName", "%" + placeName + "%");
        sql.setParam("province", sysUser.getProvince());
        sql.setParam("city", sysUser.getCity());
        sql.setParam("district", sysUser.getDistrict());
        sql.setParam("county", sysUser.getCounty());
        sql.setParam("community", sysUser.getCommunity());
        return sqfwFormsummaryNewService.listEntity(sql);
    }
}
